package com.ming.mianshidog.aop;

import com.jd.platform.hotkey.client.callback.JdHotKeyStore;
import com.ming.mianshidog.annotation.HotKeyCache;
import com.ming.mianshidog.common.ResultUtils;
import com.ming.mianshidog.model.dto.question.QuestionQueryRequest;
import com.ming.mianshidog.model.dto.questionBank.QuestionBankQueryRequest;
import com.ming.mianshidog.model.vo.QuestionBankVO;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.lang.reflect.Field;

@Aspect
@Component
public class HotKeyCacheAspect {

    @Around("@annotation(hotKeyCache)")
    public Object addHotKey(ProceedingJoinPoint joinPoint, HotKeyCache hotKeyCache) throws Throwable {
        //获取key
        String key = hotKeyCache.key();
        if (key.equals("question_detail_")){
            key = key + joinPoint.getArgs()[0];
        }else if (key.equals("bank_detail_")){
            Object object = joinPoint.getArgs()[0];
            Field field = object.getClass().getDeclaredField("id");
            field.setAccessible(true);
            key = key + field.get(object);
        }
        //获取返回值类型
        Class<?> result = hotKeyCache.result();
        //判断热key
        if (JdHotKeyStore.isHotKey(key)) {
            //从本地缓存中获取缓存值
            Object cachedVO = JdHotKeyStore.get(key);
            if (cachedVO != null) {
                //缓存中有值，返回缓存中的值
                return ResultUtils.success(result.cast(cachedVO));
            }
        }
        return joinPoint.proceed();
    }
}
